package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.wsd.smartcarwasher.constans.Constant.*;

@Api(tags = "分帐管理")
@Controller
@CrossOrigin
public class ProrateController {
    private static final Logger logger = LoggerFactory.getLogger(ProrateController.class);

    @Resource
    private ProrateService prorateService;

    @Resource
    private MachineService machineService;

    @Resource
    private TimeTaskService timeTaskService;

    @Resource
    private OrderService orderService;

    @Resource
    private UserInfoService userInfoService;


    @Resource
    private PartnerService partnerService;

    @Resource
    private  UserCouponService userCouponService;

    @Resource
    private  CardService cardService;



    @ApiOperation(value="分账列表", notes = "分账列表", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/getAll", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getAll(@RequestParam int Page,@RequestParam Integer  PageSize,
                                @RequestParam(required = false) Integer payStatus,
                           @RequestParam(required = false) String prorateTime,
                           @RequestParam(required = false) String mobile,
                           @RequestParam(required = false) Integer partnerId,
                           @RequestParam(required = false) Integer machineId
                                ) {

        Prorate prorate = new Prorate();
        if(null!=payStatus)
            prorate.setPayStatus(payStatus);
        if(StringUtils.isNotBlank(mobile))
            prorate.setMobile(mobile);
        if(StringUtils.isNotBlank(prorateTime)){
            Date date =DateUtil.stringToDate(prorateTime,"yyyy-MM-dd");
            prorate.setProrateTime(date);
        }
        if(null!=partnerId){

            prorate.setPartnerId(partnerId);
        }
        if(null!=machineId){
            prorate.setMachineId(machineId);
        }

        List<Prorate>   ls = prorateService.getAll(prorate);

        return ReturnUtil.Success(ResultState.UPDATE_ADMIN_SUCCESS.getMsg(),new Pagination<Prorate>(Page,PageSize,ls));
    }







    @ApiOperation(value="分账列表", notes = "分账列表-删除", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/delete", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap delete(@RequestParam("prorateSn") String  prorateSn) {

        Prorate prorate = new Prorate();
        prorate.setProrateSn(prorateSn);
        prorate.setStatus(102);
        int rows =prorateService.update(prorate);

        return rows>0?ReturnUtil.Success("成功") :ReturnUtil.Error("失败");
    }


    @ApiOperation(value="异常订单手动分账处理", notes = "异常订单手动分账处理需要洗车的订单号", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/proExOrder", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap proExOrder(@RequestParam String  orderSn) {

        OrderInfo order =orderService.queryOrderInfoByOrderSn(orderSn);

        if(null ==order){
            return ReturnUtil.Error("无效订单！");
        }

        if(order.getConsumed() != 3 && order.getConsumed() != 4 ){
            return ReturnUtil.Error("不是异常订单！");
        }

        if(order.getProrateStatus() == 4){
            return ReturnUtil.Error("已退费！");
        }

        if(order.getPartnerId()== null){
            return ReturnUtil.Error("此订单无需分账！");
        }

        Machine machine = machineService.queryMachineById(order.getMachineId());
        String partner_trade_no = OrderCodeFactory.getOrderCode(machine.getId().longValue());
        List<OrderInfo> ls = new ArrayList<>();
        order.setProrateSn(partner_trade_no);
        ls.add(order);

        int price =  order.getPayPrice().movePointRight(2).multiply(machine.getProfitRatio()).intValue();

        Map<String, String> res=timeTaskService.cashWithdrawal(price,order.getPartnerId(),partner_trade_no,machine.getId());

        if(res == null){
            return ReturnUtil.Error("运营商不存在");
        }

        int rows =  timeTaskService.processRes(res,ls,partner_trade_no,order.getPartnerId(),price,machine.getId());

        if(rows>0){
            Partner partner = this.partnerService.getPartnerById(order.getPartnerId());
            if (partner != null) {
                BigDecimal accountBefore = partner.getAccount();
                BigDecimal account = order.getPayPrice().multiply(machine.getProfitRatio()).add(accountBefore);
                partner.setAccount(account);
                if (this.partnerService.updatePartner(partner) == 0) {
                    logger.info(String.format("fail to add profit to partner, partnerId [ %s ], account before [ %s ], account after [ %s ], profitRate [ %s ]", partner.getId(), accountBefore, account, machine.getProfitRatio()));
                }
            }
        }
        return rows>0?ReturnUtil.Success("成功") :ReturnUtil.Error("失败");
    }


    @ApiOperation(value="分账测试", notes = "分账测试", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/test", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap test(@RequestParam String  orderSn) {
        if(!orderSn.equals("lyj")){
            return ReturnUtil.Success("成功");
        }
        String partner_trade_no = OrderCodeFactory.getOrderCode(51L);
        Map<String, String> transferMap  =
                timeTaskService.cashWithdrawal(500,18,partner_trade_no,51);
        return ReturnUtil.Success("成功",transferMap);
    }


    @ApiOperation(value="异常订单手动分账处理", notes = "需要的是  分账列表中的账单号", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/proExProrateOrder", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap proExProrateOrder(@RequestParam String  prorateSn) {

        Prorate order =prorateService.queryById(prorateSn);

        if(null ==order){
            return ReturnUtil.Error("无效订单！");
        }

        if(order.getPayStatus() ==0){
            return ReturnUtil.Error("未支付！");
        }
        //int price =  order.getPayPrice().movePointRight(2).multiply(machine.getProfitRatio()).intValue();
        Map<String, String> res=timeTaskService.cashWithdrawal(order.getAmount().movePointRight(2).intValue(),
                order.getPartnerId(),
                order.getProrateSn(),order.getMachineId());
        if (res!=null &&res.size()>0
                && res.get("result_code").equals("SUCCESS")
                && res.get("return_code").equals("SUCCESS")) {
            order.setPayStatus(0);
            order.setDesc("成功");
            prorateService.update(order);
            logger.info("手动分账成功:"+order.getProrateSn());
            return ReturnUtil.Success("成功");

        }else if(res ==null || res.get("result_code").equals("FAIL")) {
            String msg = res ==null ? "未知原因" : res.get("err_code_des");
            return ReturnUtil.Error(msg);
        }
        return ReturnUtil.Error("失败");
    }


    @ApiOperation(value="异常订单退款给客户", notes = "异常订单退款给客户", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/refundOrder", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap refundOrder(@RequestParam String  orderSn) {

        OrderInfo order =orderService.queryOrderInfoByOrderSn(orderSn);

        if(null ==order){
            return ReturnUtil.Error("无效订单！");
        }

        /*if(order.getConsumed() != 3 ||order.getConsumed() != 4 ){
            return ReturnUtil.Error("不是异常订单！");
        }*/
        if(order.getPayStatus()==0){
            return ReturnUtil.Error("未付款！");
        }

        if(order.getProrateStatus() == 4){
            return ReturnUtil.Error("已退费！");
        }

        String partner_trade_no = OrderCodeFactory.getOrderCode(order.getMachineId().longValue());
        if(order.getCardId()!=null){
          int row =  cardService.rollBackUserCard(order);
          orderService.refundOrder(orderSn,partner_trade_no);
          return  row == 0 ? ReturnUtil.Error("退款失败"):ReturnUtil.Success("退款成功");

        }

        int price =  order.getPayPrice().movePointRight(2).intValue();
        UserInfo user = userInfoService.findById(order.getUserId());

        Map<String, String> res = timeTaskService.cashWithdrawalByUser(price,partner_trade_no,user);

        if (res!=null &&res.size()>0
                && res.get("result_code").equals("SUCCESS")
                && res.get("return_code").equals("SUCCESS")) {
            logger.info(user.getUserId()+":退款成功："+price);
            //改变订单状态
            orderService.refundOrder(orderSn,partner_trade_no);
            //返还优惠卷
            if(StringUtils.isNotBlank(order.getUserCouponId())){
                logger.info(user.getUserId()+":返还优惠卷："+order.getUserCouponId());
                userCouponService.rollBackUserCoupon(order.getUserCouponId());
            }
            return ReturnUtil.Success("退款成功");
        }else if(res ==null || res.get("result_code").equals("FAIL")) {
            String msg = res ==null ? "未知原因" : res.get("err_code_des");
            logger.info(user.getUserId()+":退款成功："+price+":"+msg);
            return  ReturnUtil.Error("退款失败");
        }
        return  ReturnUtil.Error("退款失败");
    }


    @ApiOperation(value="根据id获取", notes = "根据id获取", produces = "application/json", response = Prorate.class)
    @RequestMapping(value = "/v1/prorate/queryById", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryById(@RequestParam("prorateSn") String  prorateSn) {
        return ReturnUtil.Success("成功",prorateService.queryById(prorateSn));
    }


}
